package com.ice.delay.task.controller;

import com.ice.delay.task.core.model.DelayTaskUser;
import com.ice.delay.task.service.DelayTaskUserService;
import com.ice.delay.task.vo.req.LoginVoReq;
import com.ice.delay.task.vo.res.LoginVoRes;
import com.ice.framework.common.annotation.AutoResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author wangwei
 * @Date 2023/5/9 16:04
 */
@Controller
public class LoginController {

    public static final String LOGIN_USER = "login_user";

    @Autowired
    private DelayTaskUserService delayTaskUserService;

    @RequestMapping("/toLogin")
    public String toLogin() {

        return "/login";
    }

    @RequestMapping("/")
    public String index() {
        return "/index";
    }

    @AutoResult
    @ResponseBody
    @RequestMapping("login")
    public LoginVoRes login(@RequestBody @Valid LoginVoReq loginVoReq, HttpSession httpSession) {
        DelayTaskUser delayTaskUser = delayTaskUserService.login(loginVoReq);
        LoginVoRes loginVoRes = new LoginVoRes();
        loginVoRes.setId(delayTaskUser.getId());
        loginVoRes.setName(delayTaskUser.getName());
        loginVoRes.setAccountCode(delayTaskUser.getAccountCode());
        httpSession.setAttribute(LOGIN_USER, loginVoRes);
        httpSession.setMaxInactiveInterval(60 * 60); // 设置一个小时后过期
        return loginVoRes;
    }

    @GetMapping("logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute(LOGIN_USER);
        return "redirect:/toLogin";
    }
}
